<?php

namespace App\Http\Controllers\Api\Distribution;

use App\Commission;
use App\CommissionDetail;
use App\DistributionApplication;
use App\DistributionConfig;
use App\DistributionList;
use App\DistributionRule;
use App\DistributionSignedUser;
use App\DistributionTeam;
use App\DistributionWithdraw;
use App\Http\Services\FileManager;
use App\Http\Services\MerchantManager;
use App\Http\Services\UserManager;
use App\Orders;
use App\User;
use App\UserInfo;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use DB;

use App\Http\Controllers\Controller;

class DistributionController extends Controller
{
    //Admin Used
    /**
     * 设置分销规则
     * @param Request $request
     * @return JsonResponse
     */
    public function setDistributionRule(Request $request){
        $id                       = $request->input('id');
        $rule_name                = $request->input('rule_name');
        $grade                    = $request->input('grade',1);
        $firstRatio               = $request->input('first_ratio',0);
        $secondaryRatio           = $request->input('secondary_ratio',0);
        $threeRatio               = $request->input('three_ratio',0);
        $status                   = $request->input('status');

        if ($id) {
            $newDistributionRule = DistributionRule::whereId($id)->first();
        } else {
            $newDistributionRule = null;
        }
        if(!$newDistributionRule)
            $newDistributionRule = new DistributionRule();

        $newDistributionRule->rule_name                 = $rule_name  ? $rule_name : '';
        $newDistributionRule->grade                     = $grade  ? $grade : 0;
        $newDistributionRule->first_ratio               = $firstRatio ? $firstRatio :0;
        $newDistributionRule->secondary_ratio           = $secondaryRatio ? $secondaryRatio : 0;
        $newDistributionRule->three_ratio               = $threeRatio ? $threeRatio : 0;
        $newDistributionRule->status                    = $status ? 1 : 0;
        $newDistributionRule->save();
        return response()->json(['level' => 'success','message' => '设置成功','data' => $newDistributionRule]);
    }

    /**
     * 全局设置分销层级与最低提现金额
     * @param Request $request
     * @return JsonResponse
     */
    public function setCommonValue(Request $request){
        $highestLevel             = $request->input('highest_level',1);
        $minimal_withdraw_limit   = $request->input('minimal_withdraw_limit',0);
        if (!is_numeric($highestLevel))
            return $this->parameterError();
        if (!is_numeric($minimal_withdraw_limit))
            return $this->parameterError();
        $first = DistributionConfig::first();
        if (!$first){
            $first = new DistributionConfig();
        }
        $first->highest_level           = $highestLevel;
        $first->minimal_withdraw_limit  = $minimal_withdraw_limit;
        $first->save();
        return $this->successResponse();

    }

    public function getCommonValue(Request $request){

        $first = DistributionConfig::first();
        if (!$first){
            $first = new DistributionConfig();
            $first->save();
        }

        return $this->successResponse('success',$first);

    }

    /**
     * 获取分销商
     * @param Request $request
     * @return JsonResponse
     */
    public function getDistributionUserList(Request $request){
        $page   = $request->input('page',1);
        $limit  = $request->input('limit',10);
        $type   = $request->input('type');
        $keyword  = $request->input('keyword');
        $page_info = [
            'limit'=>$limit,
            'page'=>$page,
            'total'=>0
        ];
        $page = $page - 1;
        /** @var DistributionList $data */
        $data = DistributionList::where('id','>',0);
        if (is_numeric($type)){
            $data = $data->whereType($type);
        }
        if ($keyword){
            $user_id1   = UserInfo::where('nickname','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();
            $user_id2   = User::where('phone','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();
            $ids = array_merge($user_id1,$user_id2);
            $ids = array_unique($ids);

            $data   = $data->whereIn('user_id',$ids)
                ->orWhere('name','like','%'.trim($keyword).'%')
                ->orWhere('phone','like','%'.trim($keyword).'%');
        }
        $page_info['total']=$data->count();
        $data = $data->limit($limit)->offset($page * $limit)->get();

        if(count($data) > 0){
            foreach ($data as $item){
                /** @var DistributionList $item */
                $item->img_url = FileManager::getImgUrl($item->img_id);

                $distributionRule = DistributionRule::whereId($item->rule_id)->first();
                $item->distribution_name = $distributionRule ? $distributionRule->rule_name : "-";

                $thatCommissions = Commission::whereUserId($item->user_id)->first();
                $item->available_money = $thatCommissions ? $thatCommissions->available_money : 0;
            }
        }

        return response()->json(['level'=>'success','message'=>'success','data'=>$data,'page_info'=>$page_info]);
    }

    /**
     * 获取分销商的下级
     * @param Request $request
     * @return JsonResponse
     */
    public function getDistributionNextUser(Request $request){
        $user_id= $request->input('user_id');
        $page   = $request->input('page',1);
        $limit  = $request->input('limit',10);
        $page_info = [
            'limit'=>$limit,
            'page'=>$page,
            'total'=>0
        ];
        $page = $page - 1;

        $distributionTeamsUserIds = DistributionTeam::whereUserId($user_id)->pluck("next_user_id")->toArray();

        $dataLists = DistributionList::whereIn("user_id",$distributionTeamsUserIds);

        $page_info['total']=$dataLists->count();

        $dataLists = $dataLists->orderBy("settling_time","desc")->limit($limit)->offset($page * $limit)->get();

        if(count($dataLists) > 0){
            foreach ($dataLists as $distributionList){
                $distributionList->img_url = FileManager::getImgUrl($distributionList->img_id);
                $thatCommission = Commission::whereUserId($distributionList->user_id)->first();
                if($thatCommission){
                    $distributionList->available_money = $thatCommission->available_money;
                }else{
                    $distributionList->available_money = 0;
                }

                $distributionRule = DistributionRule::whereId($distributionList->rule_id)->first();
                $distributionList->distribution_name = $distributionRule ? $distributionRule->rule_name : "-";
            }
        }

        return response()->json(['level'=>'success','message'=>'success','data'=>$dataLists,'page_info'=>$page_info]);
    }

    /**
     * 获取分销商审核
     * @param Request $request
     * @return JsonResponse
     */
    public function getDistributionReviewList(Request $request){
        $page   = $request->input('page',1);
        $limit  = $request->input('limit',10);
        $keyword  = $request->input('keyword');
        $review  = $request->input('review');
        $page_info = [
            'limit'=>$limit,
            'page'=>$page,
            'total'=>0
        ];
        $page = $page - 1;
        /** @var DistributionApplication $data */
        $data = DistributionApplication::where('id','>',0);
        if ($keyword){
            $user_id1   = UserInfo::where('nickname','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();
            $user_id2   = User::where('phone','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();
            $ids = array_merge($user_id1,$user_id2);
            $ids = array_unique($ids);

            $data   = $data->whereIn('user_id',$ids)
                ->orWhere('name','like','%'.trim($keyword).'%')
                ->orWhere('phone','like','%'.trim($keyword).'%');
        }
        if (is_numeric($review)){
            $data = $data->whereReview($review);
        }
        $page_info['total']=$data->count();
        $data = $data->limit($limit)->offset($page * $limit)->get();
        return response()->json(['level'=>'success','message'=>'success','data'=>$data,'page_info'=>$page_info]);
    }

    /**
     * 分销商审核
     * @param Request $request
     * @return JsonResponse
     */
    public function reviewDistributionApplication(Request $request){
        $id     = $request->input('id');
        $review = $request->input('review');
        if (!$id)
            return $this->parameterError();
        if (!in_array($review,[1,2]))
            return $this->parameterError();
        try {
            DB::beginTransaction();
            $record = DistributionApplication::whereId($id)->lockForUpdate()->first();
            if (!$record){
                DB::rollBack();
                return $this->dataError();
            }

            if ($record->review != 0){
                DB::rollBack();
                return $this->errorResponse('你已经操作过了');
            }
            $record->review = $review;
            $record->save();
            if ($review == 1 ){
                $d_list = DistributionList::whereUserId($record->user_id)->first();
                if (!$d_list){
                    $user_info          = UserInfo::getUserInfo($record->user_id);
                    $d_list = new DistributionList();
                    $d_list->user_id    = $record->user_id;
                    $d_list->img_id     = $user_info ? $user_info->photo_id : 0;
                }
                $d_list->name       = $record->name;
                $d_list->phone      = $record->phone;
                $d_list->type       = 1;
                $d_list->settling_time = date('Y-m-d H:i:s');
                $d_list->save();
            }
            DB::commit();
        } catch (\Exception $exception){
            DB::rollBack();
            \Log::error($exception->getMessage());
            \Log::error($exception->getTraceAsString());
            return $this->errorResponse($exception->getMessage());
        }

        return $this->successResponse();

    }

    public function setDistributionSignedUser(Request $request){
        $phone      = $request->input('phone');
        $name       = $request->input('name');
        if (!$phone)
            return $this->parameterError();

        $record = DistributionList::wherePhone($phone)->first();
        if(!$record){
            $record = new DistributionList();
            $record->phone      = $phone;
        }
        $regUser = User::wherePhone($phone)->first();
        if ($regUser){
            $record->user_id    = $regUser->id ?? 0;
            $user_info = UserInfo::whereUserId($regUser->id)->first();
            $record->img_id = $user_info->photo_id ?? 0;
        }

        $record->name       = $name ?? '';
        $record->type       = 1;
        $record->save();
        return response()->json(['level' => 'success','message' => '设置成功','data' => $record]);

    }


    /**
     * 查看用户佣金列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getUserRebate(Request $request){
        //获取每月开始和结束时间
        $month_first = date("Y-m-01", time());
        $month_end   = date("Y-m-t", time());

        $startTime = $request->input("start_time");
        $endTime   = $request->input("end_time");

        $page   = $request->input('page',1);
        $limit  = $request->input('limit',10);
        $userId = $request->input('user_id');
        $page_info = [
            'limit'=>$limit,
            'page'=>$page,
            'total'=>0
        ];
        $page = $page - 1;
        $data = CommissionDetail::where("id",">",0);

        if(!is_null($userId) && $userId != "" && $userId != 0){
            $data = $data->whereUserId($userId);
        }

        if(!is_null($startTime) && !is_null($endTime)){
            $data = $data->whereBetween("arrival_time",[$startTime,$endTime]);
        }

        $page_info['total'] = $data->count();
        $data = $data->orderBy('updated_at','desc')
            ->limit($limit)->offset($page * $limit)->get();

        if(!is_null($userId) && $userId != "" && $userId != 0) {
            //分销商信息
            $thatDistribution = DistributionList::whereUserId($userId)->first();

            $totalMoney = CommissionDetail::whereUserId($userId)->whereType(1)->whereStatus(1)->sum("amount");; //累计佣金
            $monthTotalMoney = CommissionDetail::whereUserId($userId)->whereBetween("arrival_time", [$month_first, $month_end])->whereType(1)->whereStatus(1)->sum("amount");
            $monthOrderTotalMoney = CommissionDetail::whereUserId($userId)->whereBetween("arrival_time", [$month_first, $month_end])->whereType(1)->whereStatus(1)->sum("pay_amount");
        }else{
            $totalMoney = CommissionDetail::whereType(1)->whereStatus(1)->sum("amount");; //累计佣金
            $monthTotalMoney = CommissionDetail::whereBetween("arrival_time", [$month_first, $month_end])->whereType(1)->whereStatus(1)->sum("amount");
            $monthOrderTotalMoney = CommissionDetail::whereBetween("arrival_time", [$month_first, $month_end])->whereType(1)->whereStatus(1)->sum("pay_amount");
        }

        if (count($data) > 0){
            /** @var Commission $item */
            foreach ($data as $item){
                switch ($item->status){
                    case 0:
                        $item->status_name = "待结算";
                        break;
                    case 1:
                        $item->status_name = "已到账";
                        break;
                    case 2:
                        $item->status_name = "已撤销";
                        break;
                }

                $thatOrder = Orders::whereId($item->order_id)->first();
                $item->pay_time = $thatOrder ? $thatOrder->pay_time : "-";

                $userInfo = UserInfo::whereUserId($item->from_user_id)->first();
                $item->from_nickname = $userInfo ? $userInfo->nickname : "-";
            }
        }

        $result = [
            "total_money" => $totalMoney,
            "month_total_money" => $monthTotalMoney,
            "month_order_total_money" => $monthOrderTotalMoney,
            "commissions_list" => $data
        ];
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$result,'page_info'=>$page_info]);
    }

    /**
     * 获取分销规则列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getDistributionRule(Request $request){
        $page   = $request->input('page',1);
        $limit  = $request->input('limit',10);
        $page_info = [
            'limit'=>$limit,
            'page'=>$page,
            'total'=>0
        ];
        $page = $page - 1;
        $data = DistributionRule::where('id','>',0);
        $page_info['total']=$data->count();
        $data = $data->limit($limit)->offset($page * $limit)->get();
        return response()->json(['level' => 'success','message' => '获取成功','data' => $data,'page_info'=>$page_info]);
    }

    /**
     * 获取提现列表接口
     * @param Request $request
     * @return JsonResponse
     */
    public function getWithdrawsList(Request $request){
        $page    = $request->input('page',1);
        $limit   = $request->input('limit',10);
        $keyword = $request->input('keyword');
        $status  = $request->input('status');
        $page_info = [
            'limit'=>$limit,
            'page'=>$page,
            'total'=>0
        ];
        $page = $page - 1;

        $datas = DistributionWithdraw::where('id','>',0);
        if ($keyword){
            $user_id1   = UserInfo::where('nickname','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();
            $user_id2   = User::where('phone','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();
            $ids = array_merge($user_id1,$user_id2);
            $ids = array_unique($ids);

            $datas   = $datas->whereIn('user_id',$ids)
                ->orWhere('name','like','%'.trim($keyword).'%')
                ->orWhere('phone','like','%'.trim($keyword).'%');
        }
        if (is_numeric($status)){
            $datas = $datas->whereTransferStatus($status);
        }
        $page_info['total']=$datas->count();
        $datas = $datas->orderByDesc('created_at')->limit($limit)->offset($page * $limit)->get();

        if(count($datas) > 0){
            foreach ($datas as $data){
                $data->img_url = FileManager::getImgUrl($data->img_id);

                $userInfo = UserInfo::whereUserId($data->user_id)->first();
                $data->nickname = $userInfo ? $userInfo->nickname : "-";

                switch ($data->review_status){
                    case 0:
                        $data->review_status_name = "待处理";
                        break;
                    case 1:
                        $data->review_status_name = "审核通过";
                        break;
                    case 2:
                        $data->review_status_name = "审核拒绝";
                        break;
                    default:
                        $data->review_status_name = "-";
                        break;
                }

                switch ($data->transfer_status){
                    case 0:
                        $data->transfer_status_name = "待处理";
                        break;
                    case 1:
                        $data->transfer_status_name = "转账完成";
                        break;
                    case 2:
                        $data->transfer_status_name = "转账失败";
                        break;
                    case 3:
                        $data->transfer_status_name = "转账中";
                        break;
                    default:
                        $data->transfer_status_name = "-";
                        break;
                }

                switch ($data->withdrawal_way){
                    case "wechat":
                        $data->withdraws_way_name = "微信";
                        break;
                    case "cash":
                        $data->withdraws_way_name = "现金";
                        break;
                    default:
                        $data->withdraws_way_name = "-";
                        break;
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $datas,'page_info'=>$page_info]);
    }

    /**
     * 审核提现接口
     * @param Request $request
     * @return JsonResponse
     */
    public function reviewWithdrawsList(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id      = $request->input('id');
        $status  = $request->input('status');

        /** @var $thatDistributionWithdraw $thatDistributionWithdraw */
        $thatDistributionWithdraw = DistributionWithdraw::whereId($id)->first();
        if(!$thatDistributionWithdraw){
            return response()->json(['level' => 'error','message' => '数据不存在']);
        }

        if($thatDistributionWithdraw->review_status != 0){
            return response()->json(['level' => 'error','message' => '该支付订单不可再次审核']);
        }

        DB::beginTransaction();
        if($status == 1) {
            //支付执行
            $result = PaymentController::Refund($thatDistributionWithdraw);
            \Log::error("error===>" . print_r($result, true));
            if($result["return_code"] == "FAIL") {
                $thatDistributionWithdraw->transfer_status=3;
                $thatDistributionWithdraw->transfer_user_id = $MerchantUser->id;
                $thatDistributionWithdraw->transfer_remark  = "微信接口请求失败,请重试";
                $thatDistributionWithdraw->save();
                DB::commit();
                return response()->json(['level' => 'error','message' => '操作失败,付款请求错误']);
            }elseif($result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS"){
                $thatDistributionWithdraw->review_status = $status;
                $thatDistributionWithdraw->review_user_id = $MerchantUser->id;
                $thatDistributionWithdraw->save();

                $thatDistributionWithdraw->transfer_status=1;
                $thatDistributionWithdraw->transfer_user_id = $MerchantUser->id;
                $thatDistributionWithdraw->payment_no = $result["payment_no"];
                $thatDistributionWithdraw->payment_time = $result["payment_time"];
                $thatDistributionWithdraw->save();
            }elseif ($result["return_code"] == "SUCCESS" && $result["result_code"] == "FAIL"){
                if($result["err_code"]=="NAME_MISMATCH"){
                    $thatDistributionWithdraw->review_status = 2;
                    $thatDistributionWithdraw->review_user_id = $MerchantUser->id;
                    $thatDistributionWithdraw->review_remark = $result["err_code_des"];
                    $thatDistributionWithdraw->save();

                    //退回金额
                    $thatCommissions = Commission::whereUserId($thatDistributionWithdraw->user_id)->first();
                    if(!$thatCommissions){
                        DB::rollBack();
                        return response()->json(['level' => 'error','message' => '用户信息错误']);
                    }

                    $thatCommissions->available_money = $thatCommissions->available_money+$thatDistributionWithdraw->withdraws_amount;
                    $thatCommissions->save();

                }
                $thatDistributionWithdraw->transfer_status=2;
                $thatDistributionWithdraw->transfer_user_id = $MerchantUser->id;
                $thatDistributionWithdraw->transfer_remark  = $result["err_code_des"];
                $thatDistributionWithdraw->save();

                DB::commit();
                return response()->json(['level' => 'error','message' => '操作失败['.$thatDistributionWithdraw->transfer_remark."]"]);
            }
        }else{
            $thatDistributionWithdraw->review_status = 2;
            $thatDistributionWithdraw->review_user_id = $MerchantUser->id;
            $thatDistributionWithdraw->save();

            //退回金额
            $thatCommissions = Commission::whereUserId($thatDistributionWithdraw->user_id)->first();
            if(!$thatCommissions){
                DB::rollBack();
                return response()->json(['level' => 'error','message' => '用户信息错误']);
            }

            $thatCommissions->available_money = $thatCommissions->available_money+$thatDistributionWithdraw->withdraws_amount;
            $thatCommissions->save();
        }
        DB::commit();

        return response()->json(['level' => 'success','message' => '设置成功']);
    }


}
